package com.mmloo.manage.service;

import com.alibaba.fastjson.JSONObject;
import com.mmloo.common.model.User;
import com.mmloo.common.repository.CURDRepository;
import com.mmloo.common.util.DataTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

/**
 * Created by jessy on 2015/9/25.
 */
@Service
public class LoginManageService {

    @Autowired
    CURDRepository curdRepository;

    /**
     * 登录验证
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public boolean login(String username,String password) throws Exception {
        Map<String,String> hashmap = curdRepository.hscanAll(DataTable.USER_DETAIL_DATA);
        Set<Map.Entry<String,String>> entrySet = hashmap.entrySet();
        for (Map.Entry<String, String> anEntrySet : entrySet) {
            String value = anEntrySet.getValue();
            User user = JSONObject.parseObject(value, User.class);
            if (user.getUsername().equals(username.trim()) && user.getPassword().equals(password.trim())) {
                System.out.println("user exist .... ");
                return true;
            }
        }
        return false;
    }

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     * @throws Exception
     */
    public User findByUsername(String username) throws Exception {
        Map<String,String> hashmap = curdRepository.hscanAll(DataTable.USER_DETAIL_DATA);
        Set<Map.Entry<String,String>> entrySet = hashmap.entrySet();
        for (Map.Entry<String, String> anEntrySet : entrySet) {
            String value = anEntrySet.getValue();
            User user = JSONObject.parseObject(value, User.class);
            if (user.getUsername().equals(username.trim())) {
                return user;
            }
        }
        return null;
    }
}
